package com.controller;

import com.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Map;

@Controller
@RequestMapping("anno")
@SessionAttributes(value = {"name"})
public class AnnoController {
    @RequestMapping("testRequestParam")
    public String testRequestParam(@RequestParam("uname") String name){
        System.out.println(name);
        return "success";
    }
    @RequestMapping("testRequestBody")
    public String testRequestBody(@RequestBody String body){
        System.out.println(body);
        return "success";
    }
    @RequestMapping("pathVaribale/{sid}")
    public String pathVaribale(@PathVariable(name ="sid") String id){
        System.out.println(id);
        return "success";
    }

    @RequestMapping("cookieValue")
    public String cookieValue(@CookieValue(value = "JSESSIONID") String jessionId){
        System.out.println(jessionId);
        return "success";
    }
    @RequestMapping("modelAttribute")
    public String modelAttribute(Model model){
        System.out.println(model.containsAttribute("user"));
        System.out.println(model.containsAttribute("myuser"));
        Map<String, Object> stringObjectMap = model.asMap();
        User user = (User)stringObjectMap.get("user");
        System.out.println(user);
        return "success";
    }
    @RequestMapping("sessionAttribute")
    public String sessionAttribute(ModelMap model){
        model.addAttribute("name","魏明稳");
        System.out.println(model.get("name"));
        return "success";
    }
    @RequestMapping("getsessionAttribute")
    public String getsessionAttribute(ModelMap model){
        System.out.println(model.get("name"));
        return "success";
    }
    @RequestMapping("delsessionAttribute")
    public String delsessionAttribute(SessionStatus status){
        status.setComplete();//清除session
        return "success";
    }










    /*
    * 带返回值
    *    将类型User 小写为user 作为model的属性（key）
    *     本质上还是将添加属性key--value
    * */
    @ModelAttribute("myuser")//使用带返回值的，可以将默认的小写的user替换为自定义的
    public User getUser(String uname){
        System.out.println("先执行。。。。");
        User user=new User();
        user.setUname(uname);
        user.setAge(20);
       // System.out.println(user);
        return user;
    }
    /*
    * 不带返回值
    *     使用添加属性的方式
    *     */
    @ModelAttribute("myuser")
    public void getUser2(String uname,Model model1){
        User user=new User();
        user.setUname(uname);
        user.setAge(18);
        model1.addAttribute("user",user);
    }
}
